<Query Kind="Statements">
  <Namespace>System.Threading.Tasks</Namespace>
</Query>

Console.WriteLine("CPU核心数: " + Environment.ProcessorCount);
var data = Enumerable.Range(1, 10000).ToArray();
// 🔥 关键：CPU密集型任务，线程数 = CPU核心数
var parallelOptions = new ParallelOptions
{
    MaxDegreeOfParallelism = Environment.ProcessorCount
};
var stopwatch = Stopwatch.StartNew();
Parallel.ForEach(data, parallelOptions, number =>
{
    // 模拟CPU密集型计算（如数学运算、图像处理等）
    var result = CalculatePrimeFactors(number);
    // 输出当前线程信息（便于观察）
    Console.WriteLine($"处理数据 {number}，线程ID: {Thread.CurrentThread.ManagedThreadId}，结果: {result}");
});
stopwatch.Stop();
Console.WriteLine($"总耗时: {stopwatch.ElapsedMilliseconds}ms");


// 模拟CPU密集型操作
static int CalculatePrimeFactors(int number)
{
    int count = 0;
    for (int i = 2; i <= number; i++)
    {
        while (number % i == 0)
        {
            count++;
            number /= i;
        }
    }
    return count;
}